package com.zheng.oa.admin.controller.hr;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.zheng.common.base.BaseController;
import com.zheng.common.util.CamelUnderlineConverter;
import com.zheng.hr.dao.model.HrPaidLeave;
import com.zheng.hr.rpc.api.HrDictService;
import com.zheng.hr.rpc.api.HrPaidLeaveService;
import com.zheng.oa.common.constant.OaResult;
import com.zheng.oa.common.constant.OaResultConstant;
import com.zheng.upms.dao.model.UpmsUser;
import com.zheng.upms.rpc.api.UpmsUserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by IntelliJ IDEA.
 * User: xinqi
 * Date: 2017/11/16
 * Time: 11:17
 */
@Controller
@RequestMapping("/oa/hr/paidLeave")
public class HrPaidLeaveController extends BaseController {
    @Autowired
    private UpmsUserService upmsUserService;
    @Autowired
    private HrPaidLeaveService paidLeaveService;
    @Autowired
    private HrDictService dictService;

    @RequiresPermissions("oa:hr:paidLeave:read")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model) {
        return "/manage/hr/paidLeave/index.jsp";
    }

    @RequiresPermissions("oa:hr:paidLeave:read")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Object list(@RequestParam(required = false, defaultValue = "1", value = "pageNumber") int pageNumber,
                       @RequestParam(required = false, defaultValue = "10", value = "pageSize") int pageSize,
                       @RequestParam(required = false, value = "sortName") String sortName,
                       @RequestParam(required = false, value = "sortOrder") String sortOrder,
                       UpmsUser upmsUser, Integer year) {
        Wrapper<UpmsUser> wrapper = new EntityWrapper<>();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            if (sortOrder.equalsIgnoreCase("asc")) {
                wrapper = wrapper.orderBy(CamelUnderlineConverter.camel2underline(sortName), true);
            } else {
                wrapper = wrapper.orderBy(CamelUnderlineConverter.camel2underline(sortName), false);
            }
        }
        wrapper.eq("real_user", upmsUser.IS_REAL_USER);
        if (upmsUser.getOrganizationId() != null) {
            wrapper.eq("organization_id", upmsUser.getOrganizationId());
        }
        Page<UpmsUser> page = upmsUserService.selectPage(new Page<>(pageNumber, pageSize), wrapper);
        List<String> usernameList = new ArrayList<>();
        List<UpmsUser> userList = page.getRecords();
        for (UpmsUser user : userList) {
            usernameList.add(user.getUsername());
        }
        JSONArray userArray = JSONArray.parseArray(JSON.toJSONString(userList));
        if (usernameList.size() > 0) {
            //查找出状态代码
            Integer offType = Integer.parseInt(dictService.getValue("调休假", "leave_type", "0"));
//            Integer annualType = Integer.parseInt(dictService.getValue("年假", "leave_type", "1"));
            Wrapper<HrPaidLeave> paidLeaveEntityWrapper = new EntityWrapper<>();
            paidLeaveEntityWrapper.in("username", usernameList).eq("year", year);
            List<HrPaidLeave> hrPaidLeaves = paidLeaveService.selectList(paidLeaveEntityWrapper);
            for (int i = 0, size = userArray.size(); i < size; i++) {
                JSONObject userJSON = userArray.getJSONObject(i);
                String username = userJSON.getString("username");
                //年假天数
                userJSON.put("annualLeaveDays", 0);
                //调休假天数
                userJSON.put("offLeaveDays", 0);
                for (HrPaidLeave paidLeave : hrPaidLeaves) {
                    if (paidLeave.getUsername().equals(username)) {
                        if (paidLeave.getType().equals(offType)) {
                            userJSON.put("offLeaveDays", paidLeave.getDays() - paidLeave.getUsedDays());
                        } else {
                            userJSON.put("annualLeaveDays", paidLeave.getDays() - paidLeave.getUsedDays());
                            userJSON.put("paidLeaveId", paidLeave.getId());
                        }
                    }
                }
            }
        }
        int total = upmsUserService.selectCount(wrapper);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", userArray);
        result.put("total", total);
        return result;
    }

    @RequiresPermissions("oa:hr:paidLeave:update")
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public String update(Model model, String username, Integer year) {
        Integer annualType = Integer.parseInt(dictService.getValue("年假", "leave_type", "1"));
        HrPaidLeave paidLeave = paidLeaveService.selectOne(new EntityWrapper<HrPaidLeave>()
                .eq("username", username).eq("type", annualType).eq("year", year));
        if (paidLeave != null) {
            model.addAttribute("paidLeave", paidLeave);
            model.addAttribute("usedDays", paidLeave.getUsedDays());
        } else {
            model.addAttribute("usedDays", 0);
        }
        model.addAttribute("username", username);
        model.addAttribute("year", year);

        return "/manage/hr/paidLeave/update.jsp";
    }

    @RequiresPermissions("oa:hr:paidLeave:update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Object update(HrPaidLeave paidLeave) {
        Integer annualType = Integer.parseInt(dictService.getValue("年假", "leave_type", "1"));
        paidLeave.setType(annualType);
        if (paidLeave.getId() != null) {
            HrPaidLeave leave = paidLeaveService.selectById(paidLeave);
            if (leave.getUsedDays() > paidLeave.getDays()) {
                return new OaResult(OaResultConstant.FAILED, "年假不得小于已使用天数！");
            }
        }
        try {
            paidLeaveService.insertOrUpdate(paidLeave);
        } catch (Exception e) {
            return new OaResult(OaResultConstant.FAILED, e.getMessage());
        }
        return new OaResult(OaResultConstant.SUCCESS, null);
    }
}
